import axios from 'axios'
import {browserHistory} from 'react-router';

const fetch = (options) => {
    let {
        method = 'get',
        data,
        url,
        ...config
    } = options;

    for (let key in data) {
        if (data[key] === undefined || data[key] === null) {
            delete data[key];
        }
    }


    if (!config.headers) {
        config.headers = {}
    }

    if ($$.utils.getCookie('sessionId') && config.headers['x-shinemi-auth'] === undefined) {
        config.headers['x-shinemi-auth'] = $$.utils.getCookie('sessionId')
    }


    // console.log('config', config)

    switch (method.toLowerCase()) {
        case 'get':
            return axios.get(url, {
                params: data,
                ...config
            });
        case 'delete':
            return axios.delete(url, {
                data: data,
                headers: config.headers
            }, config);
        case 'post':
            return axios.post(url, data, config);
        case 'put':
            return axios.put(url, data, config);
        case 'patch':
            return axios.patch(url, data, config);
        default:
            return axios(options);
    }
}

export default function request(options) {
    return fetch(options).then((response) => {
        const {statusText, status,} = response
        let data = response.data;


        // console.log(browserHistory.getCurrentLocation());
        if (data.code !== 200) {
            throw {data};
        } else if (data.code === 200) {
            return {
                success: true,
                message: statusText,
                statusCode: status,
                ...data,
            }
        }
    }).catch((error) => {
        const {response} = error;
        let msg;
        let statusCode;
        if (error.data.code === $$.SEM.USER_NOT_LOGIN) {
            $$.utils.delCookie('sessionId', '');
            global.window.location.href = $$.url('login');
        }

        if (response && response instanceof Object) {
            const {data, statusText} = response;
            statusCode = response.status;
            msg = data.message || statusText;
        } else {
            statusCode = 600;
            msg = error.message || 'Network Error';
        }

        return Promise.reject(error.data);

    })
}